var pId=$('#pId').val();
var schedu_type='2';
$(document).ready(function(){
	initForm();
	//事件绑定
	eventBind();
});
//初始化form表单
function initForm(){
	//初始化所属医院级拉框
	initHospitalSel();
	//加载日历
	initCalendar();
}
//事件绑定
function eventBind(){
	$('#return').on('click',function(){
		redirectCall('/page/business/register/list',null);
	});
	
	//排班信息查询
	$("#queryBtn").click(function(){
		var view = $('#calendar').fullCalendar('getView');
		queryData(view.start.format("YYYY-MM-DD"),view.end.format("YYYY-MM-DD"));
	});
}
//查询医院
function initHospitalSel(){
	$.getApiClient('/baseInfo/hospitals').get().done(function(data){
		if(!data.payload){
			data.payload=[];
		}
	    multipleSelectData("hospital",data.payload, data.payload[0].id || null, {valueAttr:'id', displayAttr:'hospital_name'},'请选择');
		$('#hospital').multipleSelect({width:'100%', single: true});
		
		//医院科室下拉框联动
		$('#hospital').change(function(){
			var hosid=$(this).children('option:selected').val();
			initDepartmentSel(hosid);
		}).change();
	});
}

//初始化所属科室下拉框
function initDepartmentSel(hosId){
	if(hosId){
		$.getApiClient('/baseInfo/departments').setQuery({hospital_id:hosId}).get().done(function(data){
			if(!data.payload){
				data.payload=[];
			}
			if(data.payload.length>0){
			    multipleSelectData("department",data.payload, data.payload[0].id || null, {valueAttr:'id', displayAttr:'department_name'});
				$('#department').multipleSelect({width:'100%', single: true});
			}else{
				multipleSelectData("department",[{"id": "", "department_name": "请选择"}], null, {valueAttr:'id', displayAttr:'department_name'},"请选择");
				$('#department').multipleSelect({width:'100%', single: true});
			}
		});
	}else{
		multipleSelectData("department",[{"id": "", "department_name": "请选择"}], null, {valueAttr:'id', displayAttr:'department_name'},"请选择");
		$('#department').multipleSelect({width:'100%', single: true});
	}
	
	//科室医生下拉框联动
	$('#department').change(function(){
		var deptId=$(this).children('option:selected').val();
		initAssignDocSel(deptId);
	}).change();
}

//初始化指定医生下拉框
function initAssignDocSel(deptId){
	if(deptId){
		$.getApiClient('/consultation/doctors/{department_id}').setQuery({department_id:deptId}).get().done(function(data){
			if(!data.payload){
				data.payload=[];
			}
			if(data.payload.length>0){
			    multipleSelectData("user",data.payload, data.payload[0].id || null, {valueAttr:'id', displayAttr:'user_name'},"请选择");
				$('#user').multipleSelect({width:'100%', single: true});
			}else{
				multipleSelectData("user",[{"id": "", "user_name": "请选择"}], null, {valueAttr:'id', displayAttr:'user_name'},"请选择");
				$('#user').multipleSelect({width:'100%', single: true});
			}
		});
	}else{
		multipleSelectData("user",[{"id": "", "user_name": "请选择"}], null, {valueAttr:'id', displayAttr:'user_name'},"请选择");
		$('#user').multipleSelect({width:'100%', single: true});
	}
}

//排班类型为医生
//定义日历UI设置对象
var calendarUI={
	header: {
		left: 'prev,next today',
		center: 'title',
		right: ''
	},
	//默认周视图
	contentHeight: 570,
	defaultView:'agendaWeek',
	firstDay: 1,
	theme:false,
	allDaySlot:false,
	allDayText:'全天',
	today: ["今天"],   
	buttonText: {
    today: '今天',    
    month: '月',    
    week: '周',    
    day: '日',    
    prev: '上一周',    
    next: '下一周'    
},    
	monthNames: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
	monthNamesShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
	dayNames: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
	dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
	editable: false,
	timeFormat:'HH:mm',
	axisFormat:'HH:mm',
	slotMinutes:30,
	minTime:'8:00',
	maxTime:'21:00',
	eventLimit: false,
	titleFormat :'YYYY年 MMM D 日',
	events: []
};

//排班管理事件列表
var calendarEvent={
	eventClick: function(calEvent, jsEvent, view) {
		showRegFormDialog(calEvent);
	},
	viewRender: function (view) {       
		queryData(view.start.format("YYYY-MM-DD"),view.end.format("YYYY-MM-DD"));
	}
};
/**
 * 日历初始化
 */
function initCalendar(){
	$('#calendar').fullCalendar($.extend(calendarUI,calendarEvent));
}

function showRegFormDialog(calEvent){
	if(calEvent.detail.usable_source_num == 0){
		customTimeOutDialog('信息提示','医生的号源预约已满，不可预约',null,2000);
	}else{
		var msg = '医生【 '+calEvent.detail.doc_name+'】 可用预约数为:【'+calEvent.detail.usable_source_num+'】，是否确认预约？';
		customConfirmDialog(msg,'确认预约',null,function(){
			saveReg(calEvent);
		});
	}
}

/**
 * 排班列表查询
 */
function queryData(startDate,endDate){
	var view = $('#calendar').fullCalendar('getView');
    var extendParam = {
    	schedu_type : schedu_type,
    	start_date : view.start.format("YYYY-MM-DD"),
    	end_date : view.end.format("YYYY-MM-DD")
    }
	$.getApiClient('/scheduling/show/list').setQuery($.extend(extendParam,$("#queryForm").collect())).get().done(function(data){
		renderCalendar(data);
	});
};

/**
 * 根据排班数据渲染日历
 */
function renderCalendar(scheduleData){
	$('#calendar').fullCalendar('removeEvents');
	$.each(scheduleData, function (index, item) {
		 var event = new Object(); 
		 event.id=item.id;
		 event.title=item.doc_name+"(总:"+item.schedu_num+" 可用:"+item.usable_source_num+") "; 
		 event.start=$.dateFormat(item.schedu_date, "yyyy-MM-dd")+'T'+item.schedu_start;
		 event.end=$.dateFormat(item.schedu_date, "yyyy-MM-dd")+'T'+item.schedu_end;
		 event.allDay=false;
		 event.textColor="white";
		 if(item.usable_source_num == 0){
			 event.color='red';
			 event.backgroundColor='red';
		 }else{
			 event.color='green';
			 event.backgroundColor='green';
		 }
		 event.className ='button_pointer';
		 event.detail = item;
  		$('#calendar').fullCalendar('renderEvent', event);
  	 });
}

//挂号操作
function saveReg(calEvent){
	$.getApiClient('/register/registerDone').post({
		hospital_id:calEvent.detail.schedu_hid,
		department_id: calEvent.detail.schedu_did,
		assign_docid: calEvent.detail.doc_id,
		use_time:$.dateFormat(calEvent.detail.schedu_date, "yyyy-MM-dd"),
		patient_id:pId,
		scheduId:calEvent.detail.id
	}).done(function(data){
		if(data.code == "0"){
			BootstrapDialog.closeAll();
			customTimeOutDialog('信息提示','患者预约成功',null,2000,function(){
				$('#return').click();
			});
		}else{
			BootstrapDialog.closeAll();
			customAlertDialog(data.message, '错误提示', null, null);
		}
	});
}
